﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ecdl.demo.model.expression;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;

using System.Xml;
using System.Xml.Serialization;

namespace ecdl.demo.model.expression {
    public class ParagraphExistsExpression : WordExpression {
        private const string POSITIVE_MESSAGE = "Der gesuchte Absatz wurde gefunden.";
        private const string NEGATIVE_MESSAGE = "Der gesuchte Absatz konnte nicht gefunden werden.";
        public String Regex { get; set; }

        protected override ExpressionState Evaluate(IEnumerable<OpenXmlElement> contextElements) {
            foreach (var element in contextElements) {
                foreach (Paragraph p in GetAllParagraphs(element)) {
                    if (RegexMatches(p)) {
                        return Success(POSITIVE_MESSAGE, NEGATIVE_MESSAGE);
                    }
                }
            }
            return Fail(NEGATIVE_MESSAGE, POSITIVE_MESSAGE);
        }

        protected bool RegexMatches(string text) {
            return System.Text.RegularExpressions.Regex.IsMatch(text, Regex);
        }

        protected bool RegexMatches(Paragraph p) {
            return RegexMatches(GetText(p));
        }

    }

    public class ParagraphExistsExpressionDTO : ExpressionDTO {
        [XmlAttribute("regex")]
        public string Regex { get; set; }

        public ParagraphExistsExpressionDTO()
            : base(typeof(ParagraphExistsExpression)) {
        }
    }
}
